package com.example.factory.api.dto.assembler;

import com.example.factory.api.dto.DtoDepartment;
import com.example.factory.api.dto.form.DtoDepartmentForm;
import com.example.factory.core.domain.Department;
import com.example.factory.core.repository.DepartmentRepository;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Lei Tao
 */
@Component
public class DepartmentAssembler {
    private final DepartmentRepository departmentRepository;

    public DepartmentAssembler(DepartmentRepository departmentRepository) {
        this.departmentRepository = departmentRepository;
    }

    public List<DtoDepartment> toDtoDepartments(Page<Department> departments) {
        List<Department> content = departments.getContent();
        List<DtoDepartment> dtoDepartments = new ArrayList<>();
        for (Department department : content) {
            DtoDepartment dtoDepartment = toDtoDepartment(department);
            dtoDepartments.add(dtoDepartment);
        }
        return dtoDepartments;
    }

    public Department toDepartment(DtoDepartmentForm dtoDepartmentForm) {
        Department department;
        if (!StringUtils.isEmpty(dtoDepartmentForm.getGuid())) {
            department = departmentRepository.findByGuidAndArchivedFalse(dtoDepartmentForm.getGuid());
        } else {
            department = new Department();
        }
        department.setName(dtoDepartmentForm.getDepartmentName());
        department.setDescription(dtoDepartmentForm.getDescription());
        return department;
    }

    public DtoDepartment toDtoDepartment(Department department) {
        DtoDepartment dtoDepartment = new DtoDepartment();
        dtoDepartment.setGuid(department.getGuid());
        dtoDepartment.setDepartmentName(department.getName());
        dtoDepartment.setDescription(department.getDescription());
        return dtoDepartment;
    }
}
